package com.itheima.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.common.CustomerException;
import com.itheima.common.R;
import com.itheima.domian.User;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    //生成验证码
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取到手机号 调用工具类生成验证码  通过短信发送用户  将验证码 放入session中
        String phone = user.getPhone();
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        //Message.msg(phone, code);//发送
        log.info("code:" + code);
        // request.getSession().setAttribute("code", code);
        redisTemplate.opsForValue().set("code_" + phone, code, 2, TimeUnit.MINUTES);
        return R.success("发送成功");
    }

    //验证码进行判断
    @PostMapping("login")
    public R<User> login(@RequestBody Map<String, String> map, HttpServletRequest request) {
        //获取到验证码  进行对比是否正确
        String phone = map.get("phone");//手机号
        String code = map.get("code");//验证码
        //错误 直接 抛出错误
        //Integer sessionCode = (Integer) request.getSession().getAttribute("code");
        Integer sessionCode = (Integer) redisTemplate.opsForValue().get("code_" + phone);
        if (!StringUtils.equals(code, String.valueOf(sessionCode))) {
            throw new CustomerException("验证码错误");
        }
        //正确 进行判断是否新老用户  老用户不用创建
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getPhone, phone));
        if (user == null) {
            //新用户进行添加到  用户表
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        Long id = user.getId();
        request.getSession().setAttribute("User", id);
        //删除验证码
        redisTemplate.delete("code_" + phone);
        return R.success(user);

    }

    //退出登录
    @PostMapping("loginout")
    public R<String> loginout(HttpServletRequest request) {
        request.getSession().invalidate();
        return R.success("成功退出登录");
    }
}

